package com.example.ormsqlsplicingframe1.orm.Util;

public class StringUtil {
    public static String javaTurnSql(String s) {
        StringBuilder stringBuilder = new StringBuilder();
        int l = 0;
        int r = 0;
        while (r < s.length()) {
            //如果下一个字符是小写
            if (r + 1 < s.length() && !isUpper(s.charAt(r + 1))) {
                while (true) {
                    r++;
                    if (r == s.length()) {
                        stringBuilder.append(s.substring(l).toLowerCase());
                        return stringBuilder.toString();
                    }
                    if (isUpper(s.charAt(r))) {
                        stringBuilder.append(s.substring(l, r).toLowerCase() + "_");
                        l = r;
                        break;
                    }
                }
            } else if (r + 1 < s.length()) {//如果下个字符是连着的大写 如HTTP
                //判断是不是第一个字符，如果不判断则会出现aA 变为aa的情况 而不是a_a
                if (r == 0 && isUpper(s.charAt(r + 1))) {
                    r++;
                    stringBuilder.append(s.substring(l, r).toLowerCase() + "_");
                    l = r;
                } else {
                    while (true) {
                        r++;
                        if (r == s.length()) {
                            stringBuilder.append(s.substring(l).toLowerCase());
                            return stringBuilder.toString();
                        }
                        if (!isUpper(s.charAt(r))) {
                            r--;
                            stringBuilder.append(s.substring(l, r).toLowerCase() + "_");
                            l = r;
                            break;
                        }
                    }
                }
            } else {//如果是到达最后了
                stringBuilder.append(s.substring(l).toLowerCase());
                r++;
            }
        }
        return stringBuilder.toString();
    }


    public static String sqlTurnJava(String s) {
        if (s == null) {
            return null;
        }
        s = s.toLowerCase();
        StringBuilder sb = new StringBuilder(s.length());
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == '_') {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static boolean isUpper(char c) {
        return c >= 'A' && c <= 'Z';
    }

}
